package com.xiaoge.config;

import com.xiaoge.service.OrderService;
import com.xiaoge.typeconvert.StringToOrderConverter;
import com.xiaoge.typeconvert.StringToOrderPropertyEditor;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;

import java.beans.PropertyEditor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author <a href="mailto:1330137071@qq.com">Zhang Xiao</a>
 * @since
 */
@Configuration
public class CustomEditorConfig {

	/**
	 * jdk转换器
	 * @return
	 */
//	@Bean
//	public CustomEditorConfigurer customEditorConfigurer() {
//		CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
//
//		Map<Class<?>, Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>();
//
//		// todo 表示StringToOrderPropertyEditor可以将String类型转换成Order类型, 在Spring源码中, 如果发现当前对象是String, 而需要类型是Order, 就会使用propertyEditor进行转换
//		propertyEditorMap.put(OrderService.class, StringToOrderPropertyEditor.class);
//
//		customEditorConfigurer.setCustomEditors(propertyEditorMap);
//
//		return customEditorConfigurer;
//	}

	/**
	 * spring 类型转换器
	 * @return
	 */
	@Bean
	public ConversionServiceFactoryBean conversionService() {

		ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
		conversionServiceFactoryBean.setConverters(Collections.singleton(new StringToOrderConverter()));
		return conversionServiceFactoryBean;

	}

	/**
	 * spring 内部用的就是这个转换器SimpleTypeConverter, 它不会定义成bean
	 * @return
	 */
	public SimpleTypeConverter simpleTypeConverter() {
		SimpleTypeConverter simpleTypeConverter = new SimpleTypeConverter();

		// todo spring 第一种转换
		DefaultConversionService defaultConversionService = new DefaultConversionService();
		defaultConversionService.addConverter(new StringToOrderConverter());

		// todo jdk 转换器
		simpleTypeConverter.registerCustomEditor(OrderService.class, new StringToOrderPropertyEditor());
		simpleTypeConverter.setConversionService(defaultConversionService);

//		OrderService orderService = simpleTypeConverter.convertIfNecessary("1", OrderService.class);
//		System.out.println(orderService);

		// todo 在遇到String 转换 成 OrderService的时候, 分别去遍历调用这两个转换器, 能转换就直接返回
		return simpleTypeConverter;
	}

}
